#include <iostream>
#include <cctype>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <list>
using namespace std;

// ============ 数据结构类 ============

// 符号表项类
class SymbolTableEntry {
public:
    string variable_name;      // 变量名
    int data_type;            // 数据类型 (0=int, 1=double)
    string initial_value;     // 初始值
    int memory_offset;        // 内存偏移量
    string original_name;     // 原始变量名
    
    SymbolTableEntry() = default;
    SymbolTableEntry(const string& var_name, int type, const string& value, 
                     int offset, const string& orig_name = "")
        : variable_name(var_name), data_type(type), initial_value(value),
          memory_offset(offset), original_name(orig_name) {}
};

// 中间代码类
class IntermediateCode {
public:
    string operation;         // 操作符
    string operand1;         // 操作数1
    string operand2;         // 操作数2
    string result;           // 结果
    int basic_block_id;      // 所属基本块ID
    int line_number;         // 行号
    bool has_label;          // 是否有标签
    pair<int, bool> op1_usage_info;   // 操作数1的使用/活跃信息
    pair<int, bool> op2_usage_info;   // 操作数2的使用/活跃信息
    pair<int, bool> result_usage_info; // 结果的使用/活跃信息
    string target_code;      // 生成的目标代码
    
    IntermediateCode() = default;
    IntermediateCode(const string& op, const string& op1, const string& op2,
                     const string& res, int block_id = 0, int line = 0, bool label = false)
        : operation(op), operand1(op1), operand2(op2), result(res),
          basic_block_id(block_id), line_number(line), has_label(label) {}
};

// ============ 辅助工具类 ============

class CompilerUtils {
public:
    // 全局常量映射表
    static const map<string, string> OPERATOR_MAP;
    static const map<string, string> CONDITION_JUMP_MAP;
    
    // 字符串处理工具
    static string trimWhitespace(const string& str) {
        auto start = str.begin();
        while (start != str.end() && isspace(*start)) ++start;
        
        auto end = str.end();
        do { --end; } 
        while (distance(start, end) > 0 && isspace(*end));
        
        return string(start, end + 1);
    }
    
    // 解析指令参数
    static vector<string> parseInstructionParameters(const string& line) {
        vector<string> parameters;
        
        auto start_pos = line.find('(');
        auto end_pos = line.find(')');
        
        if (start_pos == end_pos) {
            return vector<string>(4, "E");
        }
        
        if (start_pos != string::npos && end_pos != string::npos && end_pos > start_pos) {
            string content = line.substr(start_pos + 1, end_pos - start_pos - 1);
            stringstream ss(content);
            string parameter;
            
            while (getline(ss, parameter, ',')) {
                parameters.push_back(trimWhitespace(parameter));
            }
        }
        
        return parameters;
    }
    
    // 生成寄存器名称
    static string getRegisterName(int register_id) {
        return "R" + to_string(register_id);
    }
};

// 初始化静态成员
const map<string, string> CompilerUtils::OPERATOR_MAP = {
    {"+", "add"}, {"-", "sub"}, {"*", "mul"}, {"/", "div"},
    {"==", "sete"}, {"!=", "setne"}, {"<", "setl"}, {"<=", "setle"}, 
    {">", "setg"}, {">=", "setge"}, {"&&", "and"}, {"||", "or"}, {"!", "not"}
};

const map<string, string> CompilerUtils::CONDITION_JUMP_MAP = {
    {"j==", "je"}, {"j!=", "jne"}, {"j<", "jl"}, 
    {"j<=", "jle"}, {"j>", "jg"}, {"j>=", "jge"}
};

// ============ 符号表管理类 ============

class SymbolTable {
private:
    vector<SymbolTableEntry> symbols;
    int memory_offset;
    
public:
    SymbolTable() : memory_offset(0) {}
    
    void addSymbol(const SymbolTableEntry& entry) {
        symbols.push_back(entry);
        memory_offset = max(entry.memory_offset + (entry.data_type == 0 ? 4 : 8), memory_offset);
    }
    
    SymbolTableEntry* findSymbol(const string& var_name) {
        for (auto& symbol : symbols) {
            if (symbol.variable_name == var_name) {
                return &symbol;
            }
        }
        return nullptr;
    }
    
    string getOriginalName(const string& var) const {
        if (var.length() > 2 && var.substr(0, 2) == "TB") {
            int index = atoi(var.substr(2).c_str());
            if (index >= 0 && index < symbols.size()) {
                return symbols[index].original_name;
            }
        }
        return var;
    }
    
    string getMemoryAddress(const string& var) const {
        if (var[0] != 'T') return var;
        
        for (const auto& entry : symbols) {
            if (entry.variable_name == var) {
                return "[ebp-" + to_string(entry.memory_offset) + "]";
            }
        }
        return "";
    }
    
    int getMemoryOffset() const { return memory_offset; }
    void setMemoryOffset(int offset) { memory_offset = offset; }
    const vector<SymbolTableEntry>& getSymbols() const { return symbols; }
};

// ============ 寄存器管理类 ============

class RegisterManager {
private:
    map<string, set<string>> available_locations;  // 变量可用位置(寄存器/内存)
    map<string, set<string>> register_contents;    // 寄存器中的变量
    SymbolTable* symbol_table;
    
public:
    RegisterManager(SymbolTable* st) : symbol_table(st) {}
    
    // 检查变量是否在寄存器中
    string getRegisterForVariable(const string& var) {
        if (var[0] != 'T') return var;
        
        for (const auto& location : available_locations[var]) {
            if (location[0] == 'R') {
                return location;
            }
        }
        return "";
    }
    
    // 检查变量是否在内存中
    bool isVariableInMemory(const string& var) {
        for (const auto& location : available_locations[var]) {
            if (location[0] == '[') return true;
        }
        return false;
    }
    
    // 释放变量占用的寄存器
    void releaseVariableFromRegisters(const string& var, 
                                      const map<string, pair<int, bool>>& usage_table) {
        if (var.substr(0, 2) != "TB") {
            for (int reg_id = 0; reg_id <= 2; reg_id++) {
                string reg_name = CompilerUtils::getRegisterName(reg_id);
                register_contents[reg_name].erase(var);
                available_locations[var].erase(reg_name);
            }
        }
    }
    
    // 为指令分配寄存器
    string allocateRegister(IntermediateCode* instruction, 
                           const map<string, pair<int, bool>>& usage_table,
                           int total_ir_instructions) {
        auto& ir = *instruction;
        
        // 优先复用操作数1已占用的寄存器
        if (!isalpha(ir.operation[0])) {
            for (const auto& location : available_locations[ir.operand1]) {
                if (location[0] == 'R' && 
                    register_contents[location].size() == 1 && 
                    (ir.operand1 == ir.result || !ir.op1_usage_info.second)) {
                    return location;
                }
            }
        }
        
        // 寻找空闲寄存器
        for (int reg_id = 0; reg_id <= 2; reg_id++) {
            string reg_name = CompilerUtils::getRegisterName(reg_id);
            if (register_contents[reg_name].empty()) {
                return reg_name;
            }
        }
        
        // 所有寄存器都被占用，需要选择一个进行溢出
        return spillRegister(instruction, usage_table, total_ir_instructions);
    }
    
    void updateVariableLocation(const string& var, const string& location) {
        available_locations[var].insert(location);
    }
    
    void setVariableInRegister(const string& var, const string& reg) {
        register_contents[reg] = {var};
        available_locations[var] = {reg};
    }
    
    void removeVariableFromRegister(const string& var, const string& reg) {
        register_contents[reg].erase(var);
        available_locations[var].erase(reg);
    }
    
    void clearAll() {
        available_locations.clear();
        register_contents.clear();
    }
    
    // 调试打印函数
    void printRegisterStatus() const {
        cout << "\n=============================\n";
        for (int i = 0; i <= 2; i++) {
            cout << "R" + to_string(i) << ": ";
            auto it = register_contents.find("R" + to_string(i));
            if (it != register_contents.end()) {
                for (const auto& var : it->second) {
                    cout << var << " ";
                }
            }
            cout << "\n";
        }
        cout << endl;
        
        for (const auto& entry : available_locations) {
            if (entry.second.empty()) continue;
            cout << entry.first << ": ";
            for (const auto& location : entry.second) {
                cout << location << " ";
            }
            cout << "\n";
        }
        cout << "=============================\n";
    }

private:
    string spillRegister(IntermediateCode* instruction, 
                        const map<string, pair<int, bool>>& usage_table,
                        int total_ir_instructions) {
        auto& ir = *instruction;
        set<string> candidate_registers;
        
        // 优先选择内容都已保存到内存的寄存器
        for (int reg_id = 0; reg_id <= 2; reg_id++) {
            string reg_name = CompilerUtils::getRegisterName(reg_id);
            for (const auto& var : register_contents[reg_name]) {
                if (isVariableInMemory(var)) {
                    candidate_registers.insert(reg_name);
                }
            }
        }
        
        if (candidate_registers.empty()) {
            for (int reg_id = 0; reg_id <= 2; reg_id++) {
                candidate_registers.insert(CompilerUtils::getRegisterName(reg_id));
            }
        }
        
        // 选择最优寄存器进行溢出
        string selected_register = selectOptimalRegister(candidate_registers, usage_table, total_ir_instructions);
        
        // 溢出选中寄存器中的变量
        spillVariablesFromRegister(selected_register, instruction);
        
        register_contents[selected_register].clear();
        return selected_register;
    }
    
    string selectOptimalRegister(const set<string>& candidates,
                                const map<string, pair<int, bool>>& usage_table,
                                int total_ir_instructions) {
        // 选择全部在内存中的寄存器
        for (const auto& reg : candidates) {
            bool all_in_memory = true;
            for (const auto& var : register_contents[reg]) {
                if (!isVariableInMemory(var)) {
                    all_in_memory = false;
                    break;
                }
            }
            if (all_in_memory) {
                return reg;
            }
        }
        
        // 选择使用距离最远的变量的寄存器
        int max_next_use = 0;
        string selected_register = *candidates.begin();
        
        for (const auto& reg : candidates) {
            int min_next_use = 1e9;
            for (const auto& var : register_contents[reg]) {
                auto usage_info = usage_table.find(var);
                if (usage_info != usage_table.end() && 
                    usage_info->second.first && 
                    usage_info->second.first < min_next_use) {
                    min_next_use = usage_info->second.first;
                }
            }
            if (min_next_use > max_next_use) {
                selected_register = reg;
                max_next_use = min_next_use;
                if (max_next_use >= total_ir_instructions) break;
            }
        }
        
        return selected_register;
    }
    
    void spillVariablesFromRegister(const string& reg, IntermediateCode* instruction) {
        auto& ir = *instruction;
        auto reg_vars = register_contents[reg];
        
        for (const auto& var : reg_vars) {
            if (!(var != ir.result || 
                  (var == ir.result && var == ir.operand2 && 
                   var != ir.operand1 && !register_contents[reg].count(ir.operand1)))) {
                continue;
            }
            
            // 需要溢出到内存的变量
            if (var != ir.result && !isVariableInMemory(var)) {
                string memory_addr = symbol_table->getMemoryAddress(var);
                if (memory_addr.empty()) {
                    // 为变量分配内存空间
                    SymbolTableEntry new_entry(var, var.back() == 'd' ? 1 : 0, "null", 
                                               symbol_table->getMemoryOffset());
                    symbol_table->addSymbol(new_entry);
                    memory_addr = symbol_table->getMemoryAddress(var);
                }
                instruction->target_code += "mov " + memory_addr + ", " + reg + "\n";
            }
            
            // 更新变量的可用位置
            if (var == ir.operand1 || (var == ir.operand2 && register_contents[reg].count(ir.operand1))) {
                available_locations[var] = {symbol_table->getMemoryAddress(var), reg};
            } else {
                available_locations[var] = {symbol_table->getMemoryAddress(var)};
            }
        }
    }
};

// ============ 基本块管理类 ============

class BasicBlockManager {
private:
    vector<IntermediateCode>* ir_instructions;
    vector<vector<IntermediateCode*>> basic_blocks;
    int total_ir_instructions;
    
public:
    BasicBlockManager(vector<IntermediateCode>* ir, int total) 
        : ir_instructions(ir), total_ir_instructions(total) {}
    
    void divideIntoBasicBlocks() {
        vector<bool> is_block_start(total_ir_instructions, false);
        vector<IntermediateCode*> current_block;
        
        // 标记基本块开始位置
        markBlockStarts(is_block_start);
        
        // 根据标记划分基本块
        createBlocks(is_block_start);
    }
    
    const vector<vector<IntermediateCode*>>& getBasicBlocks() const {
        return basic_blocks;
    }
    
    void markInstructionForLabel(int instruction_index) {
        if (instruction_index >= 0 && instruction_index < ir_instructions->size()) {
            (*ir_instructions)[instruction_index].has_label = true;
        }
    }

private:
    void markBlockStarts(vector<bool>& is_block_start) {
        int instruction_index = 0;
        is_block_start[instruction_index] = true;
        
        for (auto& instruction : *ir_instructions) {
            // 跳转指令后的下一条指令是新基本块的开始
            if (instruction.operation[0] == 'j' && instruction.operation.size() > 1) {
                int target = atoi(instruction.result.c_str());
                if (target < total_ir_instructions) {
                    is_block_start[target] = true;
                }
                if (instruction_index < total_ir_instructions - 1) {
                    is_block_start[instruction_index + 1] = true;
                }
            }
            
            // 无条件跳转的目标也是基本块开始
            if (instruction.operation[0] == 'j') {
                int target = atoi(instruction.result.c_str());
                if (target < total_ir_instructions) {
                    is_block_start[target] = true;
                }
            }
            
            // 读写指令也标记为基本块开始
            if (instruction.operation == "R" || instruction.operation == "W") {
                is_block_start[instruction_index] = true;
            }
            
            instruction_index++;
        }
    }
    
    void createBlocks(const vector<bool>& is_block_start) {
        vector<IntermediateCode*> current_block;
        int instruction_index = 0;
        
        while (instruction_index < total_ir_instructions) {
            current_block.clear();
            
            if (is_block_start[instruction_index]) {
                (*ir_instructions)[instruction_index].basic_block_id = basic_blocks.size();
                current_block.push_back(&(*ir_instructions)[instruction_index]);
                
                if (instruction_index == total_ir_instructions - 1) {
                    basic_blocks.push_back(current_block);
                    break;
                }
                
                instruction_index++;
                
                // 添加同一基本块中的后续指令
                while (instruction_index < total_ir_instructions && 
                       !is_block_start[instruction_index] && 
                       (*ir_instructions)[instruction_index].operation[0] != 'j' && 
                       (*ir_instructions)[instruction_index].operation[0] != 'E') {
                    (*ir_instructions)[instruction_index].basic_block_id = basic_blocks.size();
                    current_block.push_back(&(*ir_instructions)[instruction_index]);
                    instruction_index++;
                }
                
                // 处理基本块结尾的跳转或结束指令
                if (instruction_index < total_ir_instructions && 
                    !is_block_start[instruction_index] && 
                    ((*ir_instructions)[instruction_index].operation[0] == 'j' || 
                     (*ir_instructions)[instruction_index].operation[0] == 'E')) {
                    (*ir_instructions)[instruction_index].basic_block_id = basic_blocks.size();
                    current_block.push_back(&(*ir_instructions)[instruction_index]);
                    instruction_index++;
                }
                
                basic_blocks.push_back(current_block);
            } else {
                instruction_index++;
            }
        }
    }
};

// ============ 活跃变量分析类 ============

class LivenessAnalyzer {
private:
    int total_ir_instructions;
    
public:
    LivenessAnalyzer(int total) : total_ir_instructions(total) {}
    
    set<string> analyzeVariableUsageAndLiveness(vector<IntermediateCode*>& block) {
        set<string> all_variables;
        map<string, pair<int, bool>> usage_liveness_table;
        
        // 收集块中所有变量
        for (auto& instr_ptr : block) {
            auto& instr = *instr_ptr;
            if (instr.operand1[0] == 'T') all_variables.insert(instr.operand1);
            if (instr.operand2[0] == 'T') all_variables.insert(instr.operand2);
            if (instr.result[0] == 'T') all_variables.insert(instr.result);
        }
        
        // 初始化使用/活跃信息
        initializeUsageLivenessTable(all_variables, usage_liveness_table);
        
        // 反向遍历计算活跃信息
        computeLivenessInfo(block, usage_liveness_table);
        
        return all_variables;
    }

private:
    void initializeUsageLivenessTable(const set<string>& variables,
                                      map<string, pair<int, bool>>& table) {
        for (const auto& var : variables) {
            if (var.substr(0, 2) == "TB") {
                table[var] = {total_ir_instructions * 2, true};
            } else {
                table[var] = {total_ir_instructions * 2, false};
            }
        }
    }
    
    void computeLivenessInfo(vector<IntermediateCode*>& block,
                            map<string, pair<int, bool>>& usage_table) {
        for (int i = block.size() - 1; i >= 0; i--) {
            auto& instr = *block[i];
            
            if (instr.operand1[0] == 'T') {
                instr.op1_usage_info = usage_table[instr.operand1];
                usage_table[instr.operand1] = {instr.line_number, true};
            }
            
            if (instr.operand2[0] == 'T') {
                instr.op2_usage_info = usage_table[instr.operand2];
                usage_table[instr.operand2] = {instr.line_number, true};
            }
            
            if (instr.result[0] == 'T') {
                instr.result_usage_info = usage_table[instr.result];
                usage_table[instr.result] = {total_ir_instructions * 2, false};
            }
        }
    }
};

// ============ 代码生成器类 ============

class CodeGenerator {
private:
    SymbolTable* symbol_table;
    RegisterManager* register_manager;
    BasicBlockManager* block_manager;
    LivenessAnalyzer* liveness_analyzer;
    int total_ir_instructions;
    
public:
    CodeGenerator(SymbolTable* st, RegisterManager* rm, BasicBlockManager* bm,
                  LivenessAnalyzer* la, int total)
        : symbol_table(st), register_manager(rm), block_manager(bm),
          liveness_analyzer(la), total_ir_instructions(total) {}
    
    void translateBasicBlock(vector<IntermediateCode*>& block) {
        set<string> block_variables = liveness_analyzer->analyzeVariableUsageAndLiveness(block);
        map<string, pair<int, bool>> usage_table;
        
        for (auto& instr_ptr : block) {
            auto& instr = *instr_ptr;
            
            // 更新使用信息
            updateUsageTable(instr, usage_table);
            
            // 生成目标代码
            generateInstructionCode(instr_ptr, usage_table);
        }
        
        // 处理基本块结尾
        handleBlockEnd(block, block_variables, usage_table);
        
        // 清理寄存器分配状态
        register_manager->clearAll();
    }

private:
    void updateUsageTable(const IntermediateCode& instr,
                         map<string, pair<int, bool>>& usage_table) {
        if (instr.operand1[0] == 'T') usage_table[instr.operand1] = instr.op1_usage_info;
        if (instr.operand2[0] == 'T') usage_table[instr.operand2] = instr.op2_usage_info;
        if (instr.result[0] == 'T') usage_table[instr.result] = instr.result_usage_info;
    }
    
    void generateInstructionCode(IntermediateCode* instr_ptr,
                                const map<string, pair<int, bool>>& usage_table) {
        auto& instr = *instr_ptr;
        
        if (!isalpha(instr.operation[0])) {
            generateArithmeticOperation(instr_ptr, usage_table);
        } else if (instr.operation == "R") {
            generateReadOperation(instr);
        } else if (instr.operation == "W") {
            generateWriteOperation(instr);
        }
    }
    
    void generateArithmeticOperation(IntermediateCode* instr_ptr,
                                    const map<string, pair<int, bool>>& usage_table) {
        auto& instr = *instr_ptr;
        string target_register = register_manager->allocateRegister(instr_ptr, usage_table, total_ir_instructions);
        
        string operand1_location = getOperandLocation(instr.operand1);
        string operand2_location = getOperandLocation(instr.operand2);
        
        // 将第一个操作数移到目标寄存器
        if (operand1_location != target_register) {
            instr.target_code += "mov " + target_register + ", " + operand1_location + "\n";
        }
        
        // 生成运算指令
        generateOperationCode(instr, target_register, operand2_location);
        
        // 更新寄存器分配信息
        updateRegisterAllocation(instr, target_register, usage_table);
    }
    
    void generateReadOperation(IntermediateCode& instr) {
        instr.target_code += "jmp ?read(" + symbol_table->getMemoryAddress(instr.result) + ")\n";
    }
    
    void generateWriteOperation(IntermediateCode& instr) {
        instr.target_code += "jmp ?write(" + symbol_table->getMemoryAddress(instr.result) + ")\n";
    }
    
    string getOperandLocation(const string& operand) {
        string reg_location = register_manager->getRegisterForVariable(operand);
        return reg_location.empty() ? symbol_table->getMemoryAddress(operand) : reg_location;
    }
    
    void generateOperationCode(IntermediateCode& instr, const string& target_register,
                              const string& operand2_location) {
        if (instr.operation != "=") {
            if (isComparisonOperation(instr.operation)) {
                instr.target_code += "cmp " + target_register + ", " + operand2_location + "\n";
                instr.target_code += CompilerUtils::OPERATOR_MAP.at(instr.operation) + " " + target_register + "\n";
            } else {
                if (instr.operation != "!") {
                    instr.target_code += CompilerUtils::OPERATOR_MAP.at(instr.operation) + " " + target_register + ", " + operand2_location + "\n";
                } else {
                    instr.target_code += CompilerUtils::OPERATOR_MAP.at(instr.operation) + " " + target_register + "\n";
                }
            }
            register_manager->removeVariableFromRegister(instr.operand1, target_register);
        }
    }
    
    bool isComparisonOperation(const string& op) {
        return op == "==" || op == "!=" || op == "<" || op == "<=" || op == ">" || op == ">=";
    }
    
    void updateRegisterAllocation(IntermediateCode& instr, const string& target_register,
                                 const map<string, pair<int, bool>>& usage_table) {
        register_manager->removeVariableFromRegister(instr.operand2, target_register);
        register_manager->removeVariableFromRegister(instr.operand1, target_register);
        
        // 清除结果变量在其他寄存器中的分配
        for (int i = 0; i <= 2; i++) {
            string reg_name = CompilerUtils::getRegisterName(i);
            register_manager->removeVariableFromRegister(instr.result, reg_name);
        }
        
        register_manager->setVariableInRegister(instr.result, target_register);
        
        register_manager->releaseVariableFromRegisters(instr.operand1, usage_table);
        register_manager->releaseVariableFromRegisters(instr.operand2, usage_table);
    }
    
    void handleBlockEnd(vector<IntermediateCode*>& block,
                       const set<string>& block_variables,
                       const map<string, pair<int, bool>>& usage_table) {
        // 将活跃变量保存到内存
        saveActiveVariables(block, block_variables, usage_table);
        
        // 处理跳转指令
        handleJumpInstructions(block, usage_table);
    }
    
    void saveActiveVariables(vector<IntermediateCode*>& block,
                            const set<string>& block_variables,
                            const map<string, pair<int, bool>>& usage_table) {
        map<string, string> memory_save_instructions;
        for (const auto& var : block_variables) {
            auto usage_it = usage_table.find(var);
            if (usage_it != usage_table.end() && 
                usage_it->second.second && 
                !register_manager->isVariableInMemory(var)) {
                string reg = register_manager->getRegisterForVariable(var);
                if (!reg.empty()) {
                    memory_save_instructions[symbol_table->getOriginalName(var)] = 
                        "mov " + symbol_table->getMemoryAddress(var) + ", " + reg + "\n";
                }
            }
        }
        
        for (const auto& save_instr : memory_save_instructions) {
            block.back()->target_code += save_instr.second;
        }
    }
    
    void handleJumpInstructions(vector<IntermediateCode*>& block,
                               const map<string, pair<int, bool>>& usage_table) {
        auto& last_instr = *block.back();
        
        if (last_instr.operation == "j") {
            handleUnconditionalJump(last_instr);
        } else if (last_instr.operation[0] == 'j' && last_instr.operation != "jnz") {
            handleConditionalJump(last_instr, usage_table);
        } else if (last_instr.operation == "jnz") {
            handleNonZeroJump(last_instr, usage_table);
        } else if (last_instr.operation[0] == 'E' || last_instr.operation[0] == 'S') {
            handleProgramEnd(last_instr);
        }
    }
    
    void handleUnconditionalJump(IntermediateCode& instr) {
        instr.target_code += "jmp ?" + instr.result + "\n";
        block_manager->markInstructionForLabel(atoi(instr.result.c_str()));
    }
    
    void handleConditionalJump(IntermediateCode& instr,
                              const map<string, pair<int, bool>>& usage_table) {
        string op1_location = getOperandLocationForJump(instr.operand1, &instr, usage_table);
        string op2_location = getOperandLocation(instr.operand2);
        
        instr.target_code += "cmp " + op1_location + ", " + op2_location + "\n";
        instr.target_code += CompilerUtils::CONDITION_JUMP_MAP.at(instr.operation) + " ?" + instr.result + "\n";
        block_manager->markInstructionForLabel(atoi(instr.result.c_str()));
    }
    
    void handleNonZeroJump(IntermediateCode& instr,
                          const map<string, pair<int, bool>>& usage_table) {
        string op1_location = getOperandLocationForJump(instr.operand1, &instr, usage_table);
        
        instr.target_code += "cmp " + op1_location + ", 0\n";
        instr.target_code += "jne ?" + instr.result + "\n";
        block_manager->markInstructionForLabel(atoi(instr.result.c_str()));
    }
    
    void handleProgramEnd(IntermediateCode& instr) {
        instr.target_code += "halt\n";
    }
    
    string getOperandLocationForJump(const string& operand, IntermediateCode* instr,
                                    const map<string, pair<int, bool>>& usage_table) {
        string location = register_manager->getRegisterForVariable(operand);
        if (location.empty()) {
            location = symbol_table->getMemoryAddress(operand);
        }
        
        if (location == symbol_table->getMemoryAddress(operand)) {
            location = register_manager->allocateRegister(instr, usage_table, total_ir_instructions);
            instr->target_code += "mov " + location + ", " + symbol_table->getMemoryAddress(operand) + "\n";
        }
        
        return location;
    }
};

// ============ 编译器主控制类 ============

class Compiler {
private:
    SymbolTable symbol_table;
    RegisterManager register_manager;
    BasicBlockManager* block_manager;
    LivenessAnalyzer* liveness_analyzer;
    CodeGenerator* code_generator;
    
    vector<IntermediateCode> ir_instructions;
    int total_symbols;
    int temp_symbol_count;
    int total_ir_instructions;
    
public:
    Compiler() : register_manager(&symbol_table), 
                 block_manager(nullptr), 
                 liveness_analyzer(nullptr),
                 code_generator(nullptr) {}
    
    ~Compiler() {
        delete block_manager;
        delete liveness_analyzer;
        delete code_generator;
    }
    
    bool initialize() {
        string input;
        cin >> input;
        
        // 检查语法错误
        if (input == "Syntax") {
            cin >> input;  // 读取错误信息
            cout << "halt\n";
            return false;
        } else {
            total_symbols = atoi(input.c_str());
        }
        
        // 读取符号表
        if (!loadSymbolTable()) {
            return false;
        }
        
        // 读取中间代码
        if (!loadIntermediateCode()) {
            return false;
        }
        
        // 初始化组件
        initializeComponents();
        
        return true;
    }
    
    void compile() {
        // 划分基本块
        block_manager->divideIntoBasicBlocks();
        
        // 翻译每个基本块
        const auto& basic_blocks = block_manager->getBasicBlocks();
        for (auto& block : const_cast<vector<vector<IntermediateCode*>>&>(basic_blocks)) {
            code_generator->translateBasicBlock(block);
        }
        
        // 输出目标代码
        outputTargetCode();
    }

private:
    bool loadSymbolTable() {
        for (int i = 0; i < total_symbols; i++) {
            string original_name;
            int data_type, memory_offset;
            string initial_value;
            
            cin >> original_name >> data_type >> initial_value >> memory_offset;
            
            SymbolTableEntry entry("TB" + to_string(i), data_type, initial_value, 
                                   memory_offset, original_name);
            symbol_table.addSymbol(entry);
            
            // 初始化变量位置信息
            register_manager.updateVariableLocation(entry.variable_name, 
                                                    symbol_table.getMemoryAddress(entry.variable_name));
        }
        
        return true;
    }
    
    bool loadIntermediateCode() {
        cin >> temp_symbol_count >> total_ir_instructions;
        cin.ignore();
        
        for (int i = 0; i < total_ir_instructions; i++) {
            string line;
            getline(cin, line);
            auto parameters = CompilerUtils::parseInstructionParameters(line);
            
            if (parameters.size() >= 4) {
                ir_instructions.emplace_back(parameters[0], parameters[1], 
                                            parameters[2], parameters[3], 
                                            0, i, false);
            }
        }
        
        return true;
    }
    
    void initializeComponents() {
        block_manager = new BasicBlockManager(&ir_instructions, total_ir_instructions);
        liveness_analyzer = new LivenessAnalyzer(total_ir_instructions);
        code_generator = new CodeGenerator(&symbol_table, &register_manager, 
                                          block_manager, liveness_analyzer, 
                                          total_ir_instructions);
    }
    
    void outputTargetCode() {
        const auto& basic_blocks = block_manager->getBasicBlocks();
        
        for (const auto& block : basic_blocks) {
            for (const auto& instr : block) {
                if (instr->has_label) {
                    cout << "?" << instr->line_number << ":\n";
                }
                cout << instr->target_code;
            }
        }
    }
};

// ============ 主函数 ============

int main() {
    // freopen("in.txt", "r", stdin);
    Compiler compiler;
    
    if (compiler.initialize()) {
        compiler.compile();
    }
    
    return 0;
}